﻿using CoachingOrganizer.Logic.Common;
using CoachingOrganizer.Logic.Models.Tools.EmotionsPack;
using CoachingOrganizer.Toolkit.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoachingOrganizer.Logic.Logic.Tools.EmotionsPack
{
    internal class EmotionTraceLogic
    {
        private readonly EmotionTraceModel _model;
        private readonly LogicExtender _logicExtender;
        private readonly EmotionsPackLogic _upperLogic;
        private readonly List<EmotionTraceItemLogic> _emotionTraceItems = new List<EmotionTraceItemLogic>();

        public EmotionTraceModel Model
        {
            get { return _model; }
        }

        public IEnumerable<EmotionTraceItemLogic> EmotionTraceItems
        {
            get { return _emotionTraceItems; }
        }

        public EmotionTraceLogic(EmotionTraceModel model, LogicExtender logicExtender, EmotionsPackLogic upperLogic)
        {
            _model = model;
            _logicExtender = logicExtender;
            _upperLogic = upperLogic;
            model.AddNewTraceItemDelegate = AddNewTraceItem;
            model.EnumerateTraceItemsDelegate = EnumerateTraceItems;
            model.TraceItemsCollectionChanged += Model_TraceItemsCollectionChanged;
        }

        private ActionResult<IEnumerable<EmotionTraceItemLogic>> EnumerateTraceItems()
        {
            return ActionResult<IEnumerable<EmotionTraceItemLogic>>.GetValidResult(_emotionTraceItems);
        }

        public ActionResult<EmotionTraceItemLogic> AddNewTraceItem(string traceItemName, byte[] picture)
        {
            return _upperLogic.AddNewTraceItem(this, traceItemName, picture);
        }

        public void AddTraceItem(EmotionTraceItemLogic item)
        {
            _emotionTraceItems.Add(item);
            _model.ModifyTraceItemsCollection(col => col.Add(item.Model));
        }

        public ActionResult RemoveTraceItem(EmotionTraceItemLogic logicObject)
        {
            return _upperLogic.RemoveTraceItem(logicObject);
        }

        internal void CommitTraceItemRemove(EmotionTraceItemLogic item)
        {
            _emotionTraceItems.Remove(item);
            _model.ModifyTraceItemsCollection(col => col.Remove(item.Model));
        }

        private void Model_TraceItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            _upperLogic.NotifyEmotionTraceItemsCollectionChanged(e);
        }
    }
}
